package cn.wj.school.server.manager;

import cn.wj.school.app.dto.LogOutReqMsg;
import cn.wj.school.app.dto.LogoutRespMsg;
import cn.wj.school.cloud.dto.Response;
import cn.wj.school.cloud.dto.SyUserDTO;
import cn.wj.school.cloud.dubbo.JteachDubboService;
import cn.wj.school.cloud.enums.OperateType;
import cn.wj.school.common.Constants;
import cn.wj.school.common.dto.BaseMsg;
import cn.wj.school.common.enums.MsgType;
import cn.wj.school.common.manager.BaseManager;
import cn.wj.school.server.cache.UserCache;
import cn.wj.school.server.dubbo.DubboService;
import cn.wj.school.server.net.context.IoSession;
import cn.wj.school.server.net.context.SessionCloseReason;
import cn.wj.school.server.net.context.SessionManager;
import cn.wj.school.server.net.utils.ChannelUtils;
import io.netty.channel.Channel;

/**
 * 登出
 */
public class LogOutManager implements BaseManager {

    @Override
    public String beanName() {
        return MsgType.LOGINOUT.getBeanName();
    }

    @Override
    public void handleMsg(BaseMsg msg, Channel channel) {

        LogOutReqMsg reqMsg = (LogOutReqMsg) msg;
        IoSession session = ChannelUtils.getSessionBy(channel);
        LogoutRespMsg respMsg = new LogoutRespMsg();
        /*if (StringUtils.isEmpty(reqMsg.getCard())) {
            respMsg.setSuccess(Constants.FALSE);
            respMsg.setError("系统错误，用户标识为空！");
        }*/
        SyUserDTO user = session.getUser();
        if (user == null) {
            return;
        }
        //todo 记录用户登出时间，同步到服务器
        JteachDubboService dubboService = DubboService.singletonJteachDubboService();
        Response<Boolean> logout = dubboService.registerLoginInfo(user.getId(), OperateType.LOGOUT);
        if (logout.isSuccess()) {
            //移除在线用户
            UserCache.removeFromOnline(user.getCard());
            //移除回话通道
            SessionManager.INSTANCE.sendMsgTo(session, respMsg);
            SessionManager.INSTANCE.ungisterUserDTOContext(channel, SessionCloseReason.NORMAL);
        }else {
            respMsg.setSuccess(Constants.FALSE);
            respMsg.setError(logout.getError());
            SessionManager.INSTANCE.sendMsgTo(session, respMsg);
        }

    }

    @Override
    public BaseMsg getObject() {
        return new LogOutReqMsg();
    }
}
